#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# just an  adHoc hack to pull metadata from an OD  CIF
# for proper CIF reading, you would want to use PyCifRW ...

DEBUG = 0


class ODCIF:
  def __init__(self,file):
    self.tbufsize = 80
    self.file = file
    
  def getMetadata(self):
    meta = {}
    #get these lines, in this order
    required = [
      '_cell_length_a',     
      '_cell_length_b',     
      '_cell_length_c',     
      '_cell_angle_alpha',  
      '_cell_angle_beta',       
      '_cell_angle_gamma',     
      '_diffrn_ambient_temperature ',
      '_diffrn_radiation_wavelength', 
      '_diffrn_radiation_type', 
      '_diffrn_reflns_number',
      '_diffrn_reflns_av_R_equivalents', 
      '_diffrn_reflns_av_sigmaI/netI', 
      '_diffrn_reflns_theta_min', 
      '_diffrn_reflns_theta_max', 
      '_symmetry_space_group_name_H-M',
      '_symmetry_cell_setting',
    ]
    
    buf = True
    for field in required: 
      while buf:
        buf = self.file.readline()
        if not buf.startswith(field):
          continue
        # got a match
        try:
          string = " ".join(buf.split()[1:])
          # strip SUs from measurment numbers
          if string[-1] == ")":
            if string[-3] == "(":
              string = string[0:-3]
            elif string[-4] == "(":
              string = string[0:-4]
          # strip single quotes from strings
          elif string[0] == "'" and string[-1] == "'":
            string = string[1:-1]
          # strip double quotes from strings
          elif string[0] == '"' and string[-1] == '"':
            string = string[1:-1]
          meta[field] = string
        except Exception, e:
          print field, e
        break
      if DEBUG:
        if not meta.has_key(field):
          print "Uh Oh. Missed CIF field ", field 

    return meta

	
if __name__ == '__main__':
   import sys
   fileList = sys.argv[1:]
   print fileList
   for arg in fileList:
     print arg
     file= open(arg,'rb')
     sf = ODCIF(file)
     meta =  sf.getMetadata()
     file.close()
     for key in meta.keys():
       print "%7s : %s" % (key,meta[key])

